package cn.janyd.jmall.dubbo.core.web;

import cn.janyd.common.core.vo.CommonResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.NoSuchMessageException;
import org.springframework.context.support.MessageSourceAccessor;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 改写统一返回对象中
 *
 * @author janyd
 * @since 2020/8/5 20:15
 */
public class I18nResultInterceptor implements ResponseBodyAdvice {

    private final MessageSourceAccessor messageSourceAccessor;

    public I18nResultInterceptor(MessageSourceAccessor messageSourceAccessor) {
        this.messageSourceAccessor = messageSourceAccessor;
    }

    @Override
    public boolean supports(MethodParameter returnType, Class aClass) {
        if (returnType.getMethod() == null) {
            return false;
        }
        // 只拦截返回结果为 CommonResult 类型
        return returnType.getMethod().getReturnType() == CommonResult.class;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        CommonResult<?> result = (CommonResult<?>) o;
        if (!result.isSuccess() && StringUtils.isBlank(result.getMessage())) {
            try {
                result.setMessage(this.messageSourceAccessor.getMessage(result.codeStr()));
            } catch (NoSuchMessageException e) {
                //ignore
            }
        }
        return o;
    }
}
